Hello, I have a simple vector program which has universal void** pointer. I was able to add char*, int*, long* pointers, but when I try adding float* it gives me compile error:
Vector.h
Code:
typedef struct vfunc vec_functions;
typedef struct p Private;
typedef struct v {
Private* unacessable;
vec_functions* callbacks;
}Vector;
Vector* newVector(int);
typedef void (*_addElement)(Vector*, void*);
typedef void (*_setElement)(Vector*, int, void*);
typedef void* (*_getElement)(Vector*, int);
typedef struct vfunc {
_addElement addElement;
_setElement setElement;
_getElement getElement;
} vec_functions;
Vector.c
Code:
typedef struct p {
int capacity;
int size;
void** data;
} Private;
static void doubleAmountIfFull(Vector* v) {
if ( v->unacessable->size >= v->unacessable->capacity ) {
v->unacessable->capacity *= 2;
v->unacessable->data = (void**)realloc
(v->unacessable->data,
v->unacessable->capacity);
}
}
static void __addElement(Vector *v, void *d) {
doubleAmountIfFull(v);
v->unacessable->data[v->unacessable->size] = d;
v->unacessable->size++;
}
static void __setElement(Vector *v, int index, void *d) {
if ( index < v->unacessable->capacity ||
index > v->unacessable->capacity) {
return;
} else {
v->unacessable->data[index] = d;
}
}
static void* __getElement(Vector *v, int index) {
if ( index < 0 ||
index > v->unacessable->capacity ) {
return 0x00;
} else {
return v->unacessable->data[index];
}
}
Vector* newVector(int capacity) {
Vector* v = (Vector*) malloc(sizeof(Vector));
v->unacessable = (Private*) malloc(sizeof(Private));
v->unacessable->capacity = capacity;
v->unacessable->size = 0;
v->unacessable->data = (void**) malloc(sizeof(void*)*capacity);
v->callbacks = (vec_functions*) malloc(sizeof(vec_functions));
v->callbacks->addElement = __addElement;
v->callbacks->getElement = __getElement;
v->callbacks->setElement = __setElement;
return v;
}
And the main.c file
Code:
int main(void) {
Vector* v = newVector(1000);
v->callbacks->addElement(v, (char*)"some long string");
v->callbacks->addElement(v, (int*) 10000);
v->callbacks->addElement(v, (long*) 29999999);
v->callbacks->addElement(v, (float*)3.15f);
char* c = (char*)v->callbacks->getElement(v, 0);
int* i = (int*) v->callbacks->getElement(v, 1);
long* l = (long*) v->callbacks->getElement(v, 2);
float* f = (float*) v->callbacks->getElement(v, 3);
printf("%s %d %d\n", c, i, l);
}
Compile error:
/home/ilian/QT5/Utils-in-C/main.cpp:227: error: invalid cast from type 'float' to type 'float*'
v->callbacks->addElement(v, (float*)(3.15f) );
^